package com.knowif.backend.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.knowif.backend.dto.CodeSession;
import com.knowif.backend.dto.TUserDto;
import com.knowif.backend.vo.IndexVo;
import com.knowif.enumInfo.UserEnum;
import com.knowif.pojo.*;
import com.knowif.service.*;
import com.knowif.system.model.RestBean;
import com.knowif.util.WechatMiniUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author ：Xh
 * @date ：Created in 2019/5/3 0003 22:57
 */
@Service
public class WechatMiniUserService {

    private Logger log= Logger.getLogger(WechatMiniUserService.class);//括号里面放的是当前类的class文件。

    @Autowired
    private WechatMiniUtil wechatMiniUtil;
    @Autowired
    private Tutor_service tutorDaoService;
    @Autowired
    private User_service userDaoService;
    @Autowired
    private Banner_service bannerDaoService;
    @Autowired
    private Item_service itemDaoService;
    @Autowired
    private UserWechat_service userWechat_service;

    /**
     * 微信小程序登录，不存在用户则把openid返回
     * @param tUserDto
     * @return
     */
    public RestBean<?> wechatMiniLogin(TUserDto tUserDto){
        String codeSessionStr = wechatMiniUtil.getCodeSession(tUserDto.getCode());
        CodeSession codeSession = JSONObject.parseObject(codeSessionStr, CodeSession.class);
        log.info("获取授权返回：" + codeSessionStr);
        String openid = codeSession.getOpenid();
        String unionid = codeSession.getUnionid();
        if(StringUtils.isEmpty(openid)){
            return RestBean.buildError("code无效授权失败");
        }

        TUserExample usersExample = new TUserExample();
        usersExample.createCriteria().andOpenidEqualTo(openid);
        List<TUser> users = userDaoService.selectByTUserExample(usersExample);
        TUser tUser = null;
        if(users != null && users.size() > 0){
            //存在
            tUser = users.get(0);
        }else{
            tUser = new TUser();
            BeanUtils.copyProperties(tUserDto, tUser);
            tUser.setOpenid(openid);
            tUser.setUserType(UserEnum.USER.getNumber());
            userDaoService.save(tUser);
        }
        if(unionid != null && !unionid.isEmpty() && !openid.isEmpty()){
            //加入微信表，关联unionid
            UserWechat userWechat = userWechat_service.selectByUnionId(unionid);
            if(userWechat == null){
                userWechat = new UserWechat();
                userWechat.setUnionid(unionid);
                userWechat.setMini(openid);
                userWechat_service.insertSelective(userWechat);
            }else{
                userWechat.setUnionid(unionid);
                userWechat.setMini(openid);
                userWechat_service.updateByPrimaryKeySelective(userWechat);
            }
        }
        BeanUtils.copyProperties(tUser, tUserDto);
        tUserDto.setUnionid(unionid);
        return RestBean.buildSuccess(tUserDto);
    }

    /**
     * 获取首页信息
     * @return
     */
    public RestBean<IndexVo> getIndexInfos(){
        IndexVo indexVo = new IndexVo();
        List<Banner> banners = bannerDaoService.selectBanner(new BannerExample());
        List<Item> items = itemDaoService.selectItem(new ItemExample());
        TutorInfoExample example = new TutorInfoExample();
        example.createCriteria().andIsTjEqualTo(1);
        //添加推荐排序
        example.setOrderByClause("tj_ord_num is null,tj_ord_num ASC");
        List<TutorInfo> tutorInfos = tutorDaoService.selectTutor(example);
        PageHelper.clearPage();
        indexVo.setItems(items);
        indexVo.setBanners(banners);
        indexVo.setTutorInfos(tutorInfos);
        return new RestBean<IndexVo>(RestBean.success_code, indexVo);
    }

    /**
     * 获取发现页信息
     * @return
     */
    public RestBean<IndexVo> getFoundInfos(){
        IndexVo indexVo = new IndexVo();
        TutorInfoExample example = new TutorInfoExample();
        example.createCriteria().andIsFxEqualTo(1);
        //添加发现排序
        example.setOrderByClause("fx_ord_num is null,fx_ord_num ASC");
        List<TutorInfo> tutorInfos = tutorDaoService.selectTutor(example);
        indexVo.setTutorInfos(tutorInfos);
        return new RestBean<IndexVo>(RestBean.success_code, indexVo);
    }

    /**
     * 获取发现页信息
     * @return
     */
    public RestBean<IndexVo> getFastAskInfos(){
        IndexVo indexVo = new IndexVo();
        TutorInfoExample example = new TutorInfoExample();
        example.createCriteria().andIsFastAskEqualTo(1);
        List<TutorInfo> tutorInfos = tutorDaoService.selectTutor(example);
        indexVo.setTutorInfos(tutorInfos);
        return new RestBean<>(RestBean.success_code, indexVo);
    }

    /***
     * 更新union字段
     */
    public String updateUnionInfo(String code) {
        String codeSessionStr = wechatMiniUtil.getCodeSession(code);
        CodeSession codeSession = JSONObject.parseObject(codeSessionStr, CodeSession.class);
        log.info("更新union字段获取授权返回：" + codeSessionStr);
        String openid = codeSession.getOpenid();
        String unionid = codeSession.getUnionid();
        if(!StringUtils.isEmpty(openid) && !StringUtils.isEmpty(unionid)){
            List<UserWechat> userWechats = userWechat_service.getByOpenIdAndUnionId(unionid, openid);
            if(userWechats != null && !userWechats.isEmpty()){
                UserWechat userWechat = userWechats.get(0);
                userWechat.setUnionid(unionid);
                userWechat.setMini(openid);
                userWechat_service.updateByPrimaryKeySelective(userWechat);
                return unionid;
            }
        }
        return null;
    }
}
